package org.levi.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author DevCenter
 */
public class MyNettyServer {

    private int port;

    public MyNettyServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {

        //创建boss和work 事件轮询监听线程池
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            //使用server bootstrap 创建 selector
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //配置通道和处理器
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            socketChannel.pipeline().addLast(
                                    new StringEncoder(),
                                    new JsonObjectDecoder(),
                                    new MyServerHandler());
                        }
                    })
                    .childOption(ChannelOption.SO_BACKLOG, 100);
            serverBootstrap.bind(port).sync();
        } finally {
            //workGroup.shutdownGracefully();
            //bossGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {

        MyNettyServer myNettyServer = new MyNettyServer(8889);
        myNettyServer.run();
    }
}
